/**
 * AI智能控制台
 * 统一的AI功能面板，整合预测分析、智能助手、实时监控等功能
 */

'use client'

import React, { useState, useEffect, useCallback } from 'react'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { Progress } from "@/components/ui/progress"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"
import { 
  Bot, 
  Brain, 
  TrendingUp, 
  AlertTriangle, 
  Activity, 
  Users, 
  Heart,
  Zap,
  Eye,
  Settings,
  RefreshCw,
  Download,
  MessageSquare,
  BarChart3,
  Stethoscope,
  Shield
} from 'lucide-react'
import { toast } from 'sonner'
import { 
  predictiveAI, 
  getPredictions, 
  getHighPriorityAlerts, 
  updatePredictions,
  type PredictionResult 
} from '@/lib/predictiveAI'
import { realDataService } from '@/lib/realData'
import { multimodalAI } from '@/lib/multimodalAI'
import { medicalKnowledge } from '@/lib/medicalKnowledge'
import EnhancedAIAssistant from './EnhancedAIAssistant'

interface AIDashboardProps {
  className?: string
  userId?: string
  hospitalId?: string
  onNavigateTo?: (location: { lng: number; lat: number }) => void
}

interface AIMetrics {
  totalPredictions: number
  accuracy: number
  activeModels: number
  processingTime: number
  alertsCount: number
  uptime: number
}

export const AIDashboard: React.FC<AIDashboardProps> = ({
  className = '',
  userId = 'default',
  hospitalId = 'default_hospital',
  onNavigateTo
}) => {
  const [predictions, setPredictions] = useState<PredictionResult[]>([])
  const [alerts, setAlerts] = useState<PredictionResult[]>([])
  const [isLoading, setIsLoading] = useState(true)
  const [showAssistant, setShowAssistant] = useState(false)
  const [activeTab, setActiveTab] = useState('overview')
  const [aiMetrics, setAIMetrics] = useState<AIMetrics>({
    totalPredictions: 0,
    accuracy: 0.85,
    activeModels: 5,
    processingTime: 150,
    alertsCount: 0,
    uptime: 99.8
  })

  // 实时数据更新
  useEffect(() => {
    loadAIData()
    
    // 定期更新数据
    const interval = setInterval(() => {
      loadAIData()
    }, 30000) // 30秒更新一次

    return () => clearInterval(interval)
  }, [])

  /**
   * 加载AI数据
   */
  const loadAIData = useCallback(async () => {
    try {
      setIsLoading(true)
      
      // 并行加载预测数据和告警
      const [predictionsData, alertsData] = await Promise.all([
        Promise.resolve(getPredictions()),
        Promise.resolve(getHighPriorityAlerts())
      ])

      setPredictions(predictionsData)
      setAlerts(alertsData)
      
      // 更新AI指标
      setAIMetrics(prev => ({
        ...prev,
        totalPredictions: predictionsData.length,
        alertsCount: alertsData.length,
        processingTime: Math.random() * 200 + 100 // 模拟处理时间变化
      }))

    } catch (error) {
      console.error('加载AI数据失败:', error)
      toast.error('AI数据加载失败')
    } finally {
      setIsLoading(false)
    }
  }, [])

  /**
   * 刷新预测数据
   */
  const handleRefreshPredictions = async () => {
    try {
      toast.loading('正在更新预测分析...', { id: 'refresh-predictions' })
      await updatePredictions()
      await loadAIData()
      toast.success('预测数据已更新', { id: 'refresh-predictions' })
    } catch (error) {
      toast.error('更新失败', { id: 'refresh-predictions' })
    }
  }

  /**
   * 导出AI报告
   */
  const handleExportReport = () => {
    const reportData = {
      timestamp: new Date().toISOString(),
      metrics: aiMetrics,
      predictions: predictions,
      alerts: alerts,
      summary: generateSummary()
    }

    const blob = new Blob([JSON.stringify(reportData, null, 2)], { type: 'application/json' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `ai-report-${Date.now()}.json`
    a.click()
    URL.revokeObjectURL(url)
    
    toast.success('AI报告已导出')
  }

  /**
   * 生成摘要
   */
  const generateSummary = () => {
    const criticalAlerts = alerts.filter(a => a.alertLevel === 'critical').length
    const highAlerts = alerts.filter(a => a.alertLevel === 'high').length
    
    return {
      totalPredictions: predictions.length,
      criticalAlerts,
      highAlerts,
      overallStatus: criticalAlerts > 0 ? 'critical' : 
                     highAlerts > 0 ? 'warning' : 'good',
      recommendations: [
        '持续监控高风险设备',
        '优化人员配置',
        '加强预防性维护'
      ]
    }
  }

  /**
   * 处理预测结果点击
   */
  const handlePredictionClick = (prediction: PredictionResult) => {
    // 根据预测类型执行相应操作
    switch (prediction.type) {
      case 'patient_flow':
        setActiveTab('analytics')
        break
      case 'equipment_failure':
        toast.info(`${prediction.title}: ${prediction.description}`)
        break
      case 'department_load':
        // 可以导航到相关科室
        break
      default:
        toast.info(prediction.description)
    }
  }

  /**
   * 获取指标颜色
   */
  const getMetricColor = (value: number, thresholds: { good: number; warning: number }) => {
    if (value >= thresholds.good) return 'text-green-600'
    if (value >= thresholds.warning) return 'text-yellow-600'
    return 'text-red-600'
  }

  /**
   * 获取告警级别颜色
   */
  const getAlertColor = (level: string) => {
    switch (level) {
      case 'critical': return 'destructive'
      case 'high': return 'destructive'
      case 'medium': return 'default'
      case 'low': return 'secondary'
      default: return 'default'
    }
  }

  return (
    <div className={`space-y-6 ${className}`}>
      {/* AI控制台头部 */}
      <div className="flex items-center justify-between">
        <div className="flex items-center space-x-3">
          <div className="flex items-center justify-center w-12 h-12 bg-gradient-to-r from-blue-500 to-purple-600 rounded-lg">
            <Brain className="w-6 h-6 text-white" />
          </div>
          <div>
            <h1 className="text-2xl font-bold">AI智能控制台</h1>
            <p className="text-gray-600">智能预测 • 实时监控 • 决策支持</p>
          </div>
        </div>
        
        <div className="flex items-center space-x-2">
          <Button 
            variant="outline" 
            size="sm"
            onClick={handleRefreshPredictions}
            disabled={isLoading}
          >
            <RefreshCw className={`w-4 h-4 mr-2 ${isLoading ? 'animate-spin' : ''}`} />
            刷新
          </Button>
          
          <Button 
            variant="outline" 
            size="sm"
            onClick={handleExportReport}
          >
            <Download className="w-4 h-4 mr-2" />
            导出报告
          </Button>
          
          <Button 
            size="sm"
            onClick={() => setShowAssistant(!showAssistant)}
            className="bg-gradient-to-r from-blue-500 to-purple-600"
          >
            <Bot className="w-4 h-4 mr-2" />
            AI助手
          </Button>
        </div>
      </div>

      {/* 关键指标卡片 */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">AI准确率</CardTitle>
            <TrendingUp className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{(aiMetrics.accuracy * 100).toFixed(1)}%</div>
            <Progress value={aiMetrics.accuracy * 100} className="mt-2" />
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">预测分析</CardTitle>
            <BarChart3 className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{aiMetrics.totalPredictions}</div>
            <p className="text-xs text-muted-foreground mt-1">
              个预测结果
            </p>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">告警状态</CardTitle>
            <AlertTriangle className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{aiMetrics.alertsCount}</div>
            <div className="flex items-center space-x-1 mt-1">
              {alerts.filter(a => a.alertLevel === 'critical').length > 0 && (
                <Badge variant="destructive" className="text-xs px-1">
                  {alerts.filter(a => a.alertLevel === 'critical').length}严重
                </Badge>
              )}
              {alerts.filter(a => a.alertLevel === 'high').length > 0 && (
                <Badge variant="secondary" className="text-xs px-1">
                  {alerts.filter(a => a.alertLevel === 'high').length}高
                </Badge>
              )}
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">系统状态</CardTitle>
            <Activity className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className={`text-2xl font-bold ${getMetricColor(aiMetrics.uptime, { good: 99, warning: 95 })}`}>
              {aiMetrics.uptime.toFixed(1)}%
            </div>
            <p className="text-xs text-muted-foreground mt-1">
              运行时间
            </p>
          </CardContent>
        </Card>
      </div>

      {/* 主要内容标签页 */}
      <Tabs value={activeTab} onValueChange={setActiveTab} className="w-full">
        <TabsList className="grid w-full grid-cols-5">
          <TabsTrigger value="overview" className="flex items-center gap-1">
            <Eye className="w-4 h-4" />
            概览
          </TabsTrigger>
          <TabsTrigger value="predictions" className="flex items-center gap-1">
            <Brain className="w-4 h-4" />
            预测分析
          </TabsTrigger>
          <TabsTrigger value="alerts" className="flex items-center gap-1">
            <AlertTriangle className="w-4 h-4" />
            智能告警
          </TabsTrigger>
          <TabsTrigger value="analytics" className="flex items-center gap-1">
            <BarChart3 className="w-4 h-4" />
            数据分析
          </TabsTrigger>
          <TabsTrigger value="medical" className="flex items-center gap-1">
            <Stethoscope className="w-4 h-4" />
            医疗AI
          </TabsTrigger>
        </TabsList>

        {/* 概览页 */}
        <TabsContent value="overview" className="space-y-4">
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            {/* 最新预测 */}
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <TrendingUp className="w-5 h-5" />
                  最新预测分析
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-3">
                  {predictions.slice(0, 3).map((prediction, index) => (
                    <div 
                      key={prediction.id}
                      className="flex items-start space-x-3 p-3 rounded-lg hover:bg-gray-50 cursor-pointer transition-colors"
                      onClick={() => handlePredictionClick(prediction)}
                    >
                      <div className="flex-shrink-0">
                        <Badge variant={getAlertColor(prediction.alertLevel)}>
                          {prediction.type === 'patient_flow' ? '患者流量' :
                           prediction.type === 'equipment_failure' ? '设备故障' :
                           prediction.type === 'department_load' ? '科室负载' : '资源优化'}
                        </Badge>
                      </div>
                      <div className="flex-1 min-w-0">
                        <p className="text-sm font-medium truncate">{prediction.title}</p>
                        <p className="text-xs text-gray-500 mt-1">{prediction.description}</p>
                        <div className="flex items-center gap-2 mt-2">
                          <span className="text-xs text-gray-400">
                            置信度: {(prediction.confidence * 100).toFixed(0)}%
                          </span>
                          <span className="text-xs text-gray-400">
                            {prediction.timeframe}
                          </span>
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
                
                {predictions.length === 0 && (
                  <div className="text-center py-8 text-gray-500">
                    <Brain className="w-12 h-12 mx-auto mb-2 opacity-30" />
                    <p>暂无预测数据</p>
                    <Button 
                      variant="outline" 
                      size="sm" 
                      className="mt-2"
                      onClick={handleRefreshPredictions}
                    >
                      生成预测
                    </Button>
                  </div>
                )}
              </CardContent>
            </Card>

            {/* 系统监控 */}
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <Activity className="w-5 h-5" />
                  系统监控
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  <div className="flex justify-between items-center">
                    <span className="text-sm">AI模型状态</span>
                    <Badge variant="secondary">{aiMetrics.activeModels} 个运行中</Badge>
                  </div>
                  
                  <div className="flex justify-between items-center">
                    <span className="text-sm">平均响应时间</span>
                    <span className="text-sm font-medium">{aiMetrics.processingTime.toFixed(0)}ms</span>
                  </div>
                  
                  <div className="space-y-2">
                    <div className="flex justify-between items-center">
                      <span className="text-sm">多模态支持</span>
                      <div className="flex gap-1">
                        <Badge variant="outline" className="text-xs">语音</Badge>
                        <Badge variant="outline" className="text-xs">图像</Badge>
                        <Badge variant="outline" className="text-xs">文本</Badge>
                      </div>
                    </div>
                  </div>
                  
                  <div className="pt-2 border-t">
                    <div className="flex justify-between items-center">
                      <span className="text-sm">今日处理量</span>
                      <span className="text-sm font-medium">1,234 次请求</span>
                    </div>
                  </div>
                </div>
              </CardContent>
            </Card>
          </div>

          {/* 快速操作 */}
          <Card>
            <CardHeader>
              <CardTitle>快速操作</CardTitle>
              <CardDescription>常用AI功能快捷入口</CardDescription>
            </CardHeader>
            <CardContent>
              <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
                <Button 
                  variant="outline" 
                  className="h-20 flex flex-col gap-2"
                  onClick={() => setShowAssistant(true)}
                >
                  <Bot className="w-6 h-6" />
                  <span className="text-sm">AI对话</span>
                </Button>
                
                <Button 
                  variant="outline" 
                  className="h-20 flex flex-col gap-2"
                  onClick={() => setActiveTab('predictions')}
                >
                  <Brain className="w-6 h-6" />
                  <span className="text-sm">预测分析</span>
                </Button>
                
                <Button 
                  variant="outline" 
                  className="h-20 flex flex-col gap-2"
                  onClick={() => setActiveTab('medical')}
                >
                  <Stethoscope className="w-6 h-6" />
                  <span className="text-sm">医疗咨询</span>
                </Button>
                
                <Button 
                  variant="outline" 
                  className="h-20 flex flex-col gap-2"
                  onClick={handleExportReport}
                >
                  <Download className="w-6 h-6" />
                  <span className="text-sm">导出报告</span>
                </Button>
              </div>
            </CardContent>
          </Card>
        </TabsContent>

        {/* 预测分析页 */}
        <TabsContent value="predictions" className="space-y-4">
          <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
            {predictions.map((prediction) => (
              <Card key={prediction.id} className="cursor-pointer hover:shadow-md transition-shadow">
                <CardHeader>
                  <div className="flex items-center justify-between">
                    <CardTitle className="text-lg">{prediction.title}</CardTitle>
                    <Badge variant={getAlertColor(prediction.alertLevel)}>
                      {prediction.alertLevel}
                    </Badge>
                  </div>
                  <CardDescription>{prediction.description}</CardDescription>
                </CardHeader>
                <CardContent>
                  <div className="space-y-3">
                    <div className="flex justify-between text-sm">
                      <span>置信度:</span>
                      <span className="font-medium">{(prediction.confidence * 100).toFixed(1)}%</span>
                    </div>
                    <div className="flex justify-between text-sm">
                      <span>时间范围:</span>
                      <span className="font-medium">{prediction.timeframe}</span>
                    </div>
                    
                    {prediction.recommendations.length > 0 && (
                      <div className="pt-2 border-t">
                        <p className="text-sm font-medium mb-1">建议措施:</p>
                        <ul className="text-xs space-y-1">
                          {prediction.recommendations.slice(0, 2).map((rec, index) => (
                            <li key={index} className="text-gray-600">• {rec}</li>
                          ))}
                        </ul>
                      </div>
                    )}
                  </div>
                </CardContent>
              </Card>
            ))}
          </div>
        </TabsContent>

        {/* 智能告警页 */}
        <TabsContent value="alerts" className="space-y-4">
          <div className="space-y-3">
            {alerts.map((alert) => (
              <Alert key={alert.id} className={
                alert.alertLevel === 'critical' ? 'border-red-200 bg-red-50' :
                alert.alertLevel === 'high' ? 'border-orange-200 bg-orange-50' :
                ''
              }>
                <AlertTriangle className="h-4 w-4" />
                <AlertTitle className="flex items-center gap-2">
                  {alert.title}
                  <Badge variant={getAlertColor(alert.alertLevel)} className="text-xs">
                    {alert.alertLevel}
                  </Badge>
                </AlertTitle>
                <AlertDescription>
                  <p className="mb-2">{alert.description}</p>
                  {alert.recommendations.length > 0 && (
                    <div>
                      <p className="font-medium text-sm mb-1">建议处理:</p>
                      <ul className="text-sm space-y-1">
                        {alert.recommendations.map((rec, index) => (
                          <li key={index}>• {rec}</li>
                        ))}
                      </ul>
                    </div>
                  )}
                  <p className="text-xs text-gray-500 mt-2">
                    创建时间: {new Date(alert.createdAt).toLocaleString()}
                  </p>
                </AlertDescription>
              </Alert>
            ))}

            {alerts.length === 0 && (
              <div className="text-center py-12">
                <Shield className="w-16 h-16 mx-auto mb-4 text-green-500" />
                <h3 className="text-lg font-medium mb-2">系统运行正常</h3>
                <p className="text-gray-500">当前没有需要处理的告警</p>
              </div>
            )}
          </div>
        </TabsContent>

        {/* 数据分析页 */}
        <TabsContent value="analytics" className="space-y-4">
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            <Card>
              <CardHeader>
                <CardTitle>AI性能指标</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  <div>
                    <div className="flex justify-between items-center mb-1">
                      <span className="text-sm">预测准确率</span>
                      <span className="text-sm font-medium">{(aiMetrics.accuracy * 100).toFixed(1)}%</span>
                    </div>
                    <Progress value={aiMetrics.accuracy * 100} />
                  </div>
                  
                  <div>
                    <div className="flex justify-between items-center mb-1">
                      <span className="text-sm">系统可用性</span>
                      <span className="text-sm font-medium">{aiMetrics.uptime.toFixed(1)}%</span>
                    </div>
                    <Progress value={aiMetrics.uptime} />
                  </div>
                  
                  <div>
                    <div className="flex justify-between items-center mb-1">
                      <span className="text-sm">响应效率</span>
                      <span className="text-sm font-medium">95.2%</span>
                    </div>
                    <Progress value={95.2} />
                  </div>
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle>使用统计</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-3">
                  <div className="flex justify-between items-center">
                    <span className="text-sm">今日AI对话</span>
                    <span className="font-medium">456 次</span>
                  </div>
                  <div className="flex justify-between items-center">
                    <span className="text-sm">预测生成</span>
                    <span className="font-medium">28 个</span>
                  </div>
                  <div className="flex justify-between items-center">
                    <span className="text-sm">图像分析</span>
                    <span className="font-medium">12 张</span>
                  </div>
                  <div className="flex justify-between items-center">
                    <span className="text-sm">语音识别</span>
                    <span className="font-medium">89 次</span>
                  </div>
                </div>
              </CardContent>
            </Card>
          </div>
        </TabsContent>

        {/* 医疗AI页 */}
        <TabsContent value="medical" className="space-y-4">
          <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <Stethoscope className="w-5 h-5" />
                  医疗知识库
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-3">
                  <div className="flex justify-between items-center">
                    <span className="text-sm">症状数据库</span>
                    <Badge variant="secondary">1,200+ 条</Badge>
                  </div>
                  <div className="flex justify-between items-center">
                    <span className="text-sm">药物信息</span>
                    <Badge variant="secondary">800+ 种</Badge>
                  </div>
                  <div className="flex justify-between items-center">
                    <span className="text-sm">疾病指南</span>
                    <Badge variant="secondary">500+ 个</Badge>
                  </div>
                  <div className="flex justify-between items-center">
                    <span className="text-sm">检查项目</span>
                    <Badge variant="secondary">300+ 项</Badge>
                  </div>
                </div>
              </CardContent>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <Heart className="w-5 h-5" />
                  智能诊疗助手
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-3">
                  <Button 
                    variant="outline" 
                    className="w-full justify-start"
                    onClick={() => setShowAssistant(true)}
                  >
                    <MessageSquare className="w-4 h-4 mr-2" />
                    症状咨询助手
                  </Button>
                  <Button 
                    variant="outline" 
                    className="w-full justify-start"
                  >
                    <Brain className="w-4 h-4 mr-2" />
                    用药指导系统
                  </Button>
                  <Button 
                    variant="outline" 
                    className="w-full justify-start"
                  >
                    <Activity className="w-4 h-4 mr-2" />
                    健康风险评估
                  </Button>
                  <Button 
                    variant="outline" 
                    className="w-full justify-start"
                  >
                    <AlertTriangle className="w-4 h-4 mr-2" />
                    急诊判断系统
                  </Button>
                </div>
              </CardContent>
            </Card>
          </div>
        </TabsContent>
      </Tabs>

      {/* AI助手浮窗 */}
      {showAssistant && (
        <EnhancedAIAssistant
          userId={userId}
          initialServiceType="medical"
          context={{ hospitalId }}
          onNavigateTo={onNavigateTo}
          className="fixed"
        />
      )}
    </div>
  )
}

export default AIDashboard